import '../prompt/prompt.css'
import Prompt from '../prompt/prompt.js'
import BasePlot from './basePlot';
import util from '../util';
/**
 * 椭圆标绘类（修复短轴长度限制问题）
 * @class
 * @augments BasePlot
 * @alias BasePlot.CreateEllipse
 */
class CreateEllipse extends BasePlot {
  constructor(viewer, style) {
    super(viewer, style);
    this.type = "ellipse";
    this.viewer = viewer;

    // 椭圆核心参数
    this.center = null; // 中心点坐标
    this.majorAxisPosition = null; // 长轴端点坐标
    this.minorAxisPosition = null; // 短轴端点坐标
    this.semiMajorAxis = 0; // 半长轴长度(米)
    this.semiMinorAxis = 0; // 半短轴长度(米)
    this.rotation = 0; // 旋转角度(弧度)
    this.minAxisLength = 1; // 最小轴长度(米)

    // 控制变量
    this.step = 0; // 绘制步骤：0-未开始 1-已选中心点 2-已选长轴 3-完成   
  

    // 实体与弹窗
    this.entity = null; // 椭圆实体
    this.prompt = null; // 提示弹窗

    this.centerPoint = null;
    this.majorAxisPoint = null;
    this.minorAxisPoint = null;
    this.controlPoints = []; // 控制点数组

    // 样式配置
    this.style = Object.assign({
      color: "#ff0000",
      colorAlpha: 0.5,
      outline: true,
      outlineColor: "#000000",
      outlineWidth: 2,
      fill: true,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      height: 0,
      // 编辑样式配置
      editPointColor: "#00ff00",
      editPointSize: 10,
      editPointOutlineColor: "#000000",
      editPointOutlineWidth: 1
    }, style);
  }

  /**
   * 安全归一化向量
   */
  safeNormalize(vector) {
    if (!vector) return null;
    const magnitude = Cesium.Cartesian3.magnitude(vector);
    if (magnitude < this.minAxisLength) return null;
    return Cesium.Cartesian3.normalize(vector, new Cesium.Cartesian3());
  }

  /**
   * 开始绘制
   * @param {Function} callback 绘制完成回调
   */
  start(callback) {
     
    // 初始化绘制状态
    this.step = 0;

  
    this.entity = null;
   

    // 初始化提示弹窗
    if (!this.prompt) {
      this.prompt = new Prompt(this.viewer, this.promptStyle);
    }
    // this.prompt.show = true;
    this.state = "startCreate";
    const that = this;

    // 初始化绘制事件处理器
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
 
 if (that.centerPoint) that.centerPoint.show = true;
    if (that.majorAxisPoint) that.majorAxisPoint.show = true;
    if (that.minorAxisPoint) that.minorAxisPoint.show = true;

    // 左键点击：绘制流程控制
    this.handler.setInputAction(function (evt) {

      const cartesian = that.getCatesian3FromPX(evt.position);
      if (!cartesian) return;

      // 步骤1：确定中心点
      if (that.step === 0) {
        that.center = cartesian;
        that.centerPoint = that.createPoint(cartesian);
        that.centerPoint.typeAttr = "center";

        that.majorAxisPoint = that.createPoint(cartesian.clone());
        that.majorAxisPosition = cartesian.clone();
        that.majorAxisPoint.typeAttr = "majorAxis";

        that.minorAxisPoint = that.createPoint(cartesian.clone());
        that.minorAxisPosition = cartesian.clone();
        that.minorAxisPoint.typeAttr = "minorAxis";

        that.step = 1;
        that.prompt.update(evt.position, "单击确定长轴端点（拖动可预览）");
        that.entity = that.createEllipseEntity();
      }
      // 步骤2：确定长轴端点
      else if (that.step === 1) {
        const vector = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());
        if (!that.safeNormalize(vector)) {
          that.prompt.update(evt.position, "长轴过短，请远离中心点");
          return;
        }
        that.majorAxisPosition = cartesian.clone();
        that.majorAxisPoint.position.setValue(cartesian);
        that.semiMajorAxis = Cesium.Cartesian3.distance(that.center, cartesian);
        that.step = 2;
        that.prompt.update(evt.position, "单击确定短轴端点（拖动可预览）");

      }

      // 步骤3：确定短轴端点（完成绘制）
      else if (that.step === 2) {
        const vector = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());
        if (!that.safeNormalize(vector)) {
          that.prompt.update(evt.position, "短轴过短，请远离中心点");
          return;
        }
        const distance = Cesium.Cartesian3.distance(that.center, cartesian);
        if (distance > that.semiMajorAxis) {
          that.prompt.update(evt.position, "短轴不能超过长轴，请重新选择");
          return;
        }
        that.minorAxisPosition = cartesian.clone();
        that.minorAxisPoint.position.setValue(cartesian);
        that.semiMinorAxis = distance;
        that.calculateRotation();
        that.step = 3;
        that.endCreate();

        if (callback) callback(that.entity);
      } else {
        if (that.entity) {
          that.endCreate();
          if (callback) callback(that.entity);
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 鼠标移动：实时预览
    this.handler.setInputAction(function (evt) {


      const cartesian = that.getCatesian3FromPX(evt.endPosition);
      if (!cartesian) return;

      // 如果尚未开始绘制步骤，则显示初始提示
      if (that.step === 0) {
        that.prompt.update(evt.endPosition, "单击开始绘制");
        return;
      }

      // 步骤1：预览长轴
      if (that.step === 1) {
        that.prompt.update(evt.endPosition, "单击确定长轴端点（拖动可预览）");
        const vector = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());
        if (that.safeNormalize(vector)) {
          that.majorAxisPoint.position.setValue(cartesian);
          that.semiMajorAxis = Cesium.Cartesian3.distance(that.center, cartesian);
        }
      }

      // 步骤2：预览短轴
      else if (that.step === 2 && that.entity) {
        that.prompt.update(evt.endPosition, "单击确定短轴端点（拖动可预览）");
        const vector = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());
        if (that.safeNormalize(vector)) {
          const distance = Cesium.Cartesian3.distance(that.center, cartesian);
          // 限制短轴长度不超过长轴
          if (distance <= that.semiMajorAxis) {
            that.minorAxisPoint.position.setValue(cartesian);
            that.semiMinorAxis = distance;
            that.calculateRotation();
          } else {
            // 如果超过长轴，将短轴限制为长轴长度
            const normalizedVector = that.safeNormalize(vector);
            const limitedPosition = Cesium.Cartesian3.add(
              that.center,
              Cesium.Cartesian3.multiplyByScalar(
                normalizedVector,
                that.semiMajorAxis,
                new Cesium.Cartesian3()
              ),
              new Cesium.Cartesian3()
            );
            that.minorAxisPoint.position.setValue(limitedPosition);
            that.semiMinorAxis = that.semiMajorAxis;
            that.calculateRotation();
          }
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 右键取消
    // this.handler.setInputAction(function (evt) {

    //   if (that.step === 1) {
 
    //     that.step = 0;
    //     that.prompt.update(evt.endPosition, "单击开始绘制");
    //   } else if (that.step === 2) {
    //     that.majorAxisPosition = that.center.clone();
    //     that.majorAxisPoint.position.setValue(that.center);
    //     that.semiMajorAxis = 0;
    //     that.step = 1;
    //     that.prompt.update(evt.endPosition, "单击确定长轴端点");
    //   }
    // }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }


  /**
   * 开始编辑模式（支持二次激活）
   */
  startEdit(callback) {
  
    if (this.state == "startEdit" || this.state == "editing" || !this.entity)
      return;
    this.state = "startEdit";

    if (!this.modifyHandler)
      this.modifyHandler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );
    let that = this;

    if (that.centerPoint) that.centerPoint.show = true;
    if (that.majorAxisPoint) that.majorAxisPoint.show = true;
    if (that.minorAxisPoint) that.minorAxisPoint.show = true;

    this.modifyHandler.setInputAction(function (evt) {
      if (!that.entity) return;
      that.state = "editing";

      let pick = that.viewer.scene.pick(evt.position);
      if (Cesium.defined(pick) && pick.id) {
        if (!pick.id.objId) that.modifyPoint = pick.id;
        that.forbidDrawWorld(true);
      } else {
        if (that.centerPoint) that.centerPoint.show = false;
        if (that.majorAxisPoint) that.majorAxisPoint.show = false;
        if (that.minorAxisPoint) that.minorAxisPoint.show = false;
        if (that.modifyHandler) {
          that.modifyHandler.destroy();
          that.modifyHandler = null;
        }
      }

    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    this.modifyHandler.setInputAction(function (evt) {
      if (!that.modifyPoint) return;
      let cartesian = that.getCatesian3FromPX(evt.endPosition);
      if (!cartesian) return;
      that.state = "editing";

      // 根据当前拖拽的点更新椭圆参数
      if (that.modifyPoint.typeAttr === 'center') {
        // 中心点拖动
        const offset = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());

        that.center = cartesian;
        that.centerPoint.position.setValue(that.center);
        that.entity.position.setValue(that.center);

        that.majorAxisPosition = Cesium.Cartesian3.add(
          that.majorAxisPosition,
          offset,
          new Cesium.Cartesian3()
        );

        that.majorAxisPoint.position.setValue(that.majorAxisPosition);

        that.minorAxisPosition = Cesium.Cartesian3.add(
          that.minorAxisPosition,
          offset,
          new Cesium.Cartesian3()
        );

        that.minorAxisPoint.position.setValue(that.minorAxisPosition);

        // that.calculateRotation();
      } else if (that.modifyPoint.typeAttr === 'majorAxis') {
        // 长轴端点拖动
        const vector = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());

        if (that.safeNormalize(vector)) {
          that.majorAxisPosition = cartesian.clone();
          that.majorAxisPoint.position.setValue(cartesian);
          that.semiMajorAxis = Cesium.Cartesian3.distance(that.center, cartesian);

          // 更新椭圆实体的半长轴属性
          if (that.entity && that.entity.ellipse) {
            that.entity.ellipse.semiMajorAxis = that.semiMajorAxis;
          }

          // 关键修复：拖动长轴时，如果长轴变得比短轴短，则同步调整短轴
          if (that.semiMajorAxis < that.semiMinorAxis) {
            const minorVector = Cesium.Cartesian3.subtract(
              that.minorAxisPosition,
              that.center,
              new Cesium.Cartesian3()
            );
            const normalizedMinorVector = that.safeNormalize(minorVector);
            if (normalizedMinorVector) {
              that.semiMinorAxis = that.semiMajorAxis;
              that.minorAxisPosition = Cesium.Cartesian3.add(
                that.center,
                Cesium.Cartesian3.multiplyByScalar(
                  normalizedMinorVector,
                  that.semiMajorAxis,
                  new Cesium.Cartesian3()
                ),
                new Cesium.Cartesian3()
              );
              that.minorAxisPoint.position.setValue(that.minorAxisPosition);

              // 更新椭圆实体的半短轴属性
              if (that.entity && that.entity.ellipse) {
                that.entity.ellipse.semiMinorAxis = that.semiMinorAxis;
              }
            }
          }

          that.calculateRotation();
        }
      } else if (that.modifyPoint.typeAttr === 'minorAxis') {
        // 短轴端点拖动
        const vector = Cesium.Cartesian3.subtract(cartesian, that.center, new Cesium.Cartesian3());

        if (that.safeNormalize(vector)) {
          const distance = Cesium.Cartesian3.distance(that.center, cartesian);

          // 关键修复：确保短轴不超过长轴
          if (distance <= that.semiMajorAxis) {
            that.minorAxisPosition = cartesian.clone();
            that.minorAxisPoint.position.setValue(cartesian);
            that.semiMinorAxis = distance;
          } else {
            // 如果拖动超过长轴长度，则将短轴限制为长轴长度
            const normalizedVector = that.safeNormalize(vector);
            const limitedPosition = Cesium.Cartesian3.add(
              that.center,
              Cesium.Cartesian3.multiplyByScalar(
                normalizedVector,
                that.semiMajorAxis,
                new Cesium.Cartesian3()
              ),
              new Cesium.Cartesian3()
            );
            that.minorAxisPosition = limitedPosition;
            that.minorAxisPoint.position.setValue(limitedPosition);
            that.semiMinorAxis = that.semiMajorAxis;
          }

          // 更新椭圆实体的半短轴属性
          if (that.entity && that.entity.ellipse) {
            that.entity.ellipse.semiMinorAxis = that.semiMinorAxis;
          }
        }
      }


      // if (that.attr && that.attr.onEditing) {
      //   that.attr.onEditing(that, that.entity);
      // }

      if (callback) callback();
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    this.modifyHandler.setInputAction(function (evt) {
      if (!that.modifyPoint) return;
      that.modifyPoint = null;
      that.forbidDrawWorld(false);
      that.state = "editing";
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }


  /**
   * 显示编辑控制点
   */
  showEditPoints() {
    if (this.centerPoint) this.centerPoint.show = true;
    if (this.majorAxisPoint) this.majorAxisPoint.show = true;
    if (this.minorAxisPoint) this.minorAxisPoint.show = true;
  }

  /**
   * 隐藏编辑控制点
   */
  hideEditPoints() {
    if (this.centerPoint) this.centerPoint.show = false;
    if (this.majorAxisPoint) this.majorAxisPoint.show = false;
    if (this.minorAxisPoint) this.minorAxisPoint.show = false;
  }

  /**
   * 创建椭圆实体
   */
  createEllipseEntity() {
    const that = this;
    const ellipse = this.viewer.entities.add({
      position: that.center,
      ellipse: {
        semiMajorAxis: new Cesium.CallbackProperty(() => that.semiMajorAxis, false),
        semiMinorAxis: new Cesium.CallbackProperty(() => that.semiMinorAxis, false),
        rotation: new Cesium.CallbackProperty(() => that.rotation, false),
        height: this.style.height,
        heightReference: this.style.heightReference,
        fill: this.style.fill,
        material: this.getFillMaterial(),
        outline: this.style.outline && this.style.heightReference !== Cesium.HeightReference.CLAMP_TO_GROUND,
        outlineColor: this.getOutlineColor(),
        outlineWidth: this.style.outlineWidth
      }
    });
    ellipse.objId = this.objId;

    // 绘制完成后注册点击激活编辑事件

    return ellipse;
  }

  /**
   * 根据参数创建椭圆实体（非交互式）
   * @param {Object} params 椭圆参数
   * @param {Cesium.Cartesian3} params.center 椭圆中心点
   * @param {Number} params.semiMajorAxis 半长轴长度（米）
   * @param {Number} params.semiMinorAxis 半短轴长度（米）
   * @param {Number} params.rotation 旋转角度（弧度）
   */
  createEllipseEntityFromParams(params) {
    this.center = params.center;
    this.semiMajorAxis = params.semiMajorAxis;
    this.semiMinorAxis = params.semiMinorAxis;
    this.rotation = params.rotation || 0;

    // 计算长轴和短轴端点位置
    // 假设长轴沿正北方向，短轴沿正东方向
    const majorAxisOffset = new Cesium.Cartesian3(0, this.semiMajorAxis, 0);
    const minorAxisOffset = new Cesium.Cartesian3(this.semiMinorAxis, 0, 0);

    // 转换为笛卡尔坐标偏移
    const ellipsoid = this.viewer.scene.globe.ellipsoid;
    const centerCartographic = ellipsoid.cartesianToCartographic(this.center);

    // 计算长轴端点
    const majorAxisCartographic = new Cesium.Cartographic(
      centerCartographic.longitude,
      centerCartographic.latitude + this.semiMajorAxis / 6378137.0, // 简化的纬度偏移
      centerCartographic.height
    );
    this.majorAxisPosition = ellipsoid.cartographicToCartesian(majorAxisCartographic);

    // 计算短轴端点
    const minorAxisCartographic = new Cesium.Cartographic(
      centerCartographic.longitude + this.semiMinorAxis / (6378137.0 * Math.cos(centerCartographic.latitude)), // 简化的经度偏移
      centerCartographic.latitude,
      centerCartographic.height
    );
    this.minorAxisPosition = ellipsoid.cartographicToCartesian(minorAxisCartographic);

    // 创建椭圆实体
    this.entity = this.createEllipseEntity()
    this.entity.objId = this.objId;

    // 创建控制点
    this.centerPoint = this.createPoint(this.center);
    this.centerPoint.typeAttr = "center";
    this.majorAxisPoint = this.createPoint(this.majorAxisPosition);
    this.majorAxisPoint.typeAttr = "majorAxis";
    this.minorAxisPoint = this.createPoint(this.minorAxisPosition);
    this.minorAxisPoint.typeAttr = "minorAxis";


    return this.entity;
  }


  getStyle() {
    let obj = {};
    let ellipse = this.entity.ellipse;
    let color = ellipse.material.color.getValue();
    obj.colorAlpha = color.alpha;
    obj.color = new Cesium.Color(
      color.red,
      color.green,
      color.blue,
      1
    ).toCssHexString();
    if (ellipse.outline) obj.outline = ellipse.outline.getValue();
    obj.outlineWidth = ellipse.outlineWidth._value;
    let outlineColor = ellipse.outlineColor.getValue();
    obj.outlineColorAlpha = outlineColor.alpha;
    obj.outlineColor = new Cesium.Color(
      outlineColor.red,
      outlineColor.green,
      outlineColor.blue,
      1
    ).toCssHexString();
    if (ellipse.height) obj.height = ellipse.height.getValue();
    if (ellipse.fill) obj.fill = ellipse.fill.getValue();
    obj.heightReference = ellipse.heightReference.getValue();
    return obj;
  }



  /**
   * 计算旋转角度
   */
  calculateRotation() {
    if (!this.center || !this.majorAxisPosition) {
      this.rotation = 0;
      return;
    }
    const centerCartographic = Cesium.Cartographic.fromCartesian(this.center);
    const majorCartographic = Cesium.Cartographic.fromCartesian(this.majorAxisPosition);
    const dx = majorCartographic.longitude - centerCartographic.longitude;
    const dy = majorCartographic.latitude - centerCartographic.latitude;
    this.rotation = isNaN(dx) || isNaN(dy) ? 0 : Math.atan2(dx, dy);
  }

  /**
   * 结束绘制
   */
  endCreate() {
 let that = this;
    that.state = "endCreate";
    
    if (that.centerPoint) that.centerPoint.show = false;
    if (that.majorAxisPoint) that.majorAxisPoint.show = false;
    if (that.minorAxisPoint) that.minorAxisPoint.show = false;
    if (that.prompt) {
      that.prompt.destroy();
      that.prompt = null;
    }
    if (that.handler) {
      that.handler.destroy();
      that.handler = null;
    }

  }




  destroy() {
 

 

    // // 销毁提示弹窗
    // if (this.prompt) {
    //   this.prompt.destroy();
    //   this.prompt = null;
    // }

    // // 重置状态
    // this.state = "none";
    // this.isDrawing = false;
  


    if (this.handler) {
      this.handler.destroy();
      this.handler = null;
    }
    if (this.modifyHandler) {
      this.modifyHandler.destroy();
      this.modifyHandler = null;
    }
    if (this.entity) {
      this.viewer.entities.remove(this.entity);
      this.entity = null;
    }

    if (this.centerPoint) {
      this.viewer.entities.remove(this.centerPoint);
      this.centerPoint = null;
    }
    if (this.majorAxisPoint) {
      this.viewer.entities.remove(this.majorAxisPoint);
      this.majorAxisPoint = null;
    }
    if (this.minorAxisPoint) {
      this.viewer.entities.remove(this.minorAxisPoint);
      this.minorAxisPoint = null;
    }

    this.style = null;
    this.modifyPoint = null;
    if (this.prompt) this.prompt.destroy();
    this.forbidDrawWorld(false);
    this.state = "no";
  }

 

  /**
   * 设置样式
   */
  setStyle(style) {
    if (!style) return;
    this.style = Object.assign(this.style, style);

    if (this.entity) {
      if (style.color || style.colorAlpha) {
        this.entity.ellipse.material = this.getFillMaterial();
      }
      if (style.height !== undefined) {
        this.entity.ellipse.height = style.height;
      }
      if (style.heightReference !== undefined) {
        this.entity.ellipse.heightReference = style.heightReference;
      }
      // if (style.outline !== undefined || style.outlineWidth !== undefined || style.outlineColor !== undefined) {
      //   if (this.style.heightReference !== Cesium.HeightReference.CLAMP_TO_GROUND) {
      //     if (style.outline !== undefined) this.entity.ellipse.outline = style.outline;
      //     if (style.outlineWidth !== undefined) this.entity.ellipse.outlineWidth = style.outlineWidth;
      //     if (style.outlineColor !== undefined) {
      //       this.entity.ellipse.outlineColor = this.getOutlineColor();
      //     }
      //   }
      // }
      if (style.outline !== undefined) {
        this.entity.ellipse.outline = style.outline;
      }
      if (style.outlineWidth !== undefined) {
        this.entity.ellipse.outlineWidth = style.outlineWidth;
      }
      if (style.outlineColor !== undefined) {
        this.entity.ellipse.outlineColor = this.getOutlineColor();
      }
    }

    // 更新控制点样式
    [this.centerPoint, this.majorAxisPoint, this.minorAxisPoint].forEach(point => {
      if (point && point.point) {
        if (style.editPointColor) {
          point.point.color = style.editPointColor instanceof Cesium.Color
            ? style.editPointColor
            : Cesium.Color.fromCssColorString(style.editPointColor);
        }
        if (style.editPointSize) point.point.pixelSize = style.editPointSize;
      }
    });
  }

  /**
   * 其他基础方法
   */
  getFillMaterial() {
    // 这里可以添加具体的填充材质逻辑
    return Cesium.Color.fromCssColorString(this.style.color).withAlpha(this.style.colorAlpha);
  }

  getOutlineColor() {
    // 这里可以添加具体的轮廓颜色逻辑
    return Cesium.Color.fromCssColorString(this.style.outlineColor);
  }

  getCatesian3FromPX(position) {
    // 这里可以添加从屏幕坐标转换为笛卡尔坐标的逻辑
    const ray = this.viewer.camera.getPickRay(position);
    return this.viewer.scene.globe.pick(ray, this.viewer.scene);
  }
  /**
   * 通过传入坐标数组创建椭圆
   * @param {Array | Object} lnglatArr 坐标数组或椭圆参数对象
   * @param {Function} callback 回调函数
   */
  createByPositions(lnglatArr, callback) {
    if (!lnglatArr) return;
    this.state = "startCreate";

    // 检查是否为椭圆参数对象（DrawEllipse1类型）
    if (lnglatArr.center && lnglatArr.semiMajorAxis && lnglatArr.semiMinorAxis !== undefined) {
      // 使用传入的参数创建椭圆
      this.createEllipseEntityFromParams({
        center: lnglatArr.center,
        semiMajorAxis: lnglatArr.semiMajorAxis,
        semiMinorAxis: lnglatArr.semiMinorAxis,
        rotation: lnglatArr.rotation || 0
      });
    } else if (Array.isArray(lnglatArr)) {
      // 处理传入的坐标数组
      let isCartesian3 = lnglatArr[0] instanceof Cesium.Cartesian3;
      let positions = [];
      if (isCartesian3) {
        positions = lnglatArr;
      } else {
        positions = util.lnglatsToCartesians(lnglatArr);
      }
      if (!positions || positions.length < 2) return;

      this.center = positions[0].clone();
      this.majorAxisPosition = positions[1].clone();
      this.minorAxisPosition = positions[2] ? positions[2].clone() : positions[1].clone(); // 如果没有第三个点，则使用第二个点

      // 计算半轴长度
      this.semiMajorAxis = Cesium.Cartesian3.distance(this.center, this.majorAxisPosition);
      this.semiMinorAxis = Cesium.Cartesian3.distance(this.center, this.minorAxisPosition);

      // 计算旋转角度
      this.calculateRotation();

      // 创建椭圆实体
      this.entity = this.createEllipseEntity();

      // 创建控制点
      this.centerPoint = this.createPoint(this.center);
      this.centerPoint.typeAttr = "center";
      this.majorAxisPoint = this.createPoint(this.majorAxisPosition);
      this.majorAxisPoint.typeAttr = "majorAxis";
      this.minorAxisPoint = this.createPoint(this.minorAxisPosition);
      this.minorAxisPoint.typeAttr = "minorAxis";
    }

    this.state = "endCreate";
    if (callback) callback(this.entity);
  }

  /**
   * 当前步骤结束
   */
  done() {
    if (this.state == "startCreate") {
      this.destroy();
    } else if (this.state == "creating") {
      this.destroy();
    } else if (this.state == "startEdit" || this.state == "editing") {
      this.endEdit();
    }
  }

  /**
   * 结束编辑
   * @param {Function} callback 回调函数
   */
   endEdit(callback) {
    // 确保所有编辑点都被隐藏
    if (this.centerPoint) {
      this.centerPoint.show = false;
      // 从viewer.entities中移除点实体以确保完全清理
      // this.viewer.entities.remove(this.centerPoint);
      // this.centerPoint = null;
    }
    if (this.majorAxisPoint) {
      this.majorAxisPoint.show = false;
      // 从viewer.entities中移除点实体以确保完全清理
      // this.viewer.entities.remove(this.majorAxisPoint);
      // this.majorAxisPoint = null;
    }
    if (this.minorAxisPoint) {
      this.minorAxisPoint.show = false;
      // 从viewer.entities中移除点实体以确保完全清理
      // this.viewer.entities.remove(this.minorAxisPoint);
      // this.minorAxisPoint = null;
    }

    //  if (this.editHandler) {
    //   this.editHandler.destroy();
    //   this.editHandler = null;
    // }
    // 销毁修改处理器
    if (this.modifyHandler) {
      this.modifyHandler.destroy();
      this.modifyHandler = null;
    }

    // 重置修改点引用
    this.modifyPoint = null;

    // 恢复世界绘制
    this.forbidDrawWorld(false);

    // 更新状态
    this.state = "endEdit";

    // 执行回调
    if (callback) callback(this.entity);
  }
}


export default CreateEllipse;